<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			*{
				margin:0;
				padding:0;
			}
			#box{
				height:100px;
				width:100px;
				background-color: orange;
				position: fixed;
				left:0;
				top:0;
			}
		</style>
	</head>
	<body>
		<div id="box"></div>
		<script>
			let box=document.getElementById("box");
			let beginX,beginY;
			let html=document.documentElement||document.body;
			//鼠标进入小盒子，按下
			box.onmousedown=function(e){
				//初始坐标
				beginX=e.offsetX;
				beginY=e.offsetY;
				
				//全局移动鼠标，小盒子跟着鼠标走
				window.addEventListener("mousemove",move);
				//鼠标抬起的时候，小盒子停止移动
				window.addEventListener("mouseup",up);
			}
			
			//移动的每个瞬间，都要求小盒子的位置
			function move(e){
				let endX=e.clientX;
				let endY=e.clientY;
				
				let maxW=html.clientWidth-box.offsetWidth;//最大移动宽
				let maxH=html.clientHeight-box.offsetHeight;//最大移动高度
				
				let resultX=endX-beginX;
				let resultY=endY-beginY;
				
				// if(resultX>maxW){
				// 	resultX=maxW;
				// }
				// if(resultX<=0){
				// 	resultX=0;
				// }
				
				//设置范围
				resultX=resultX>maxW?maxW:(resultX<=0?0:resultX);
				resultY=resultY>maxH?maxH:(resultY<=0?0:resultY);
				
				box.style.left=resultX+'px';
				box.style.top=resultY+'px';
			}
			
			function up(){
				//移除移动事件
				window.removeEventListener("mousemove",move);
				//移除抬起事件
				window.removeEventListener("mouseup",up);
			}
		</script>
	</body>
</html>
